package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.team;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.base.models.OrderLogContent;
import com.gzhryc.shared_device.common.payment.dao.db.PayAccountGroup;
import com.gzhryc.shared_device.common.payment.dao.db.WXTransferMoneyOrder;
import com.gzhryc.shared_device.common.payment.services.PayAccountGroupService;
import com.gzhryc.shared_device.common.payment.services.WXTransferMoneyOrderService;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.dao.db.UserTransferMoneyOrder;
import com.gzhryc.shared_device.oem.code.user.dao.db.UserTransferMoneyOrderLog;
import com.gzhryc.shared_device.oem.code.user.dao.enums.UserTransferMoneyOrderEnum;
import com.gzhryc.shared_device.oem.code.user.services.UserTransferMoneyOrderLogService;
import com.gzhryc.shared_device.oem.code.user.services.UserTransferMoneyOrderService;
import com.gzhryc.shared_device.oem.code.user.services.dto.UserTransferMoneyOrderSearch;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;

public class UserTransferMoneyOrderController {

	 	@Route(value = { "/team/user/transfer_money_order/list.html" })
	    public String list(HttpServletRequest request) {
	        request.setAttribute("stateList",UserTransferMoneyOrderEnum.State.values());
	        request.setAttribute("handleTypeList",UserTransferMoneyOrderEnum.HandleType.values());
	        return "/team/user/transfer_money_order/list.html";
	    }

	    @Route(value = "/team/user/transfer_money_order/list.data")
	    public ListResult<UserTransferMoneyOrder> listData(HttpServletRequest request) {
	        ListResult<UserTransferMoneyOrder> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
	        UserTransferMoneyOrderSearch search = WebUtils.getParameter(request, UserTransferMoneyOrderSearch.class);
	        Integer pageNo = WebUtils.getInteger(request, "page", 1);
	        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
	        
	        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
	        if(loginUser != null) {
	        	List<PayAccountGroup> accountGroupList = PayAccountGroupService.self().findByUserId(loginUser.getId());
	        	if(accountGroupList != null && accountGroupList.size() > 0) {
	        		List<Long> accountGroupIds = new ArrayList<Long>();
	        		for(PayAccountGroup accountGroup : accountGroupList) {
	        			accountGroupIds.add(accountGroup.getId());
	        		}
	        		
	        		search.setAccountGroupIds(accountGroupIds);
	        		
	        		List<UserTransferMoneyOrder>  transferMoneyOrderList =  UserTransferMoneyOrderService.self()
		        			.findJoinBySearch(search, pageNo, pageLimit);
		        	result.getBody().setTotal(UserTransferMoneyOrderService.self().countJoinBySearch(search));
		        	 
		        	if(transferMoneyOrderList != null && transferMoneyOrderList.size() > 0){
		 	            result.setCode(DtoConstants.SUCCESS,null);
		 	            result.getBody().setData(transferMoneyOrderList);
		 	        }
	        	}
	        }
	        return result;
	    }
	    
	    @Route(value = { "/team/user/transfer_money_order/info.html" })
	    public String info(HttpServletRequest request) {
	    	String tradeNo = WebUtils.getString(request,"tradeNo");
	    	User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
	    	if(loginUser != null) {
		        UserTransferMoneyOrder order = UserTransferMoneyOrderService.self().getJoinByTradeNo(tradeNo);
		        if(order != null) {
		        	PayAccountGroup accountGroup = PayAccountGroupService.self().getById(order.getAccountGroupId());
		        	if(accountGroup != null && accountGroup.getUserId() != null 
		        			&& accountGroup.getUserId().equals(loginUser.getId())) {
		        		String resDomain = PropertyTools.get().getString("resDomain");
			            if(StringTools.isNotBlank(order.getReceivingQrcode())){
			                order.setReceivingQrcode(WebUtils.setHttpDomain(resDomain,order.getReceivingQrcode()));
			            }
	
			            WebUtils.setAttribute(request, order);
			            WXTransferMoneyOrder wxTransferMoneyOrder = WXTransferMoneyOrderService.self().getByTradeNo(order.getTradeNo());
			            if(wxTransferMoneyOrder != null) {
			                if(StringTools.isNotBlank(wxTransferMoneyOrder.getFaceImg())){
			                    wxTransferMoneyOrder.setFaceImg(WebUtils.setHttpDomain(resDomain,wxTransferMoneyOrder.getFaceImg()));
			                }
			                request.setAttribute("transferMoneyOrder", wxTransferMoneyOrder);
			            }
		        	}
		        }
	    	}
	        return "/team/user/transfer_money_order/info.html";
	    }
	    
	    @Route(value = { "/team/user/transfer_money_order/handle.html" })
	    public String handle(HttpServletRequest request) {
	        String tradeNo = WebUtils.getString(request,"tradeNo");
	        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
	    	if(loginUser != null) {
		        UserTransferMoneyOrder order = UserTransferMoneyOrderService.self().getByTradeNo(tradeNo);
		        if(order != null) {
		        	PayAccountGroup accountGroup = PayAccountGroupService.self().getById(order.getAccountGroupId());
		        	if(accountGroup != null && accountGroup.getUserId() != null 
		        			&& accountGroup.getUserId().equals(loginUser.getId())) {
			            if(StringTools.isNotBlank(order.getReceivingQrcode())){
			                String resDomain = PropertyTools.get().getString("resDomain");
			                order.setReceivingQrcode(WebUtils.setHttpDomain(resDomain,order.getReceivingQrcode()));
			            }
			            WebUtils.setAttribute(request, order);
			            WXTransferMoneyOrder wxTransferMoneyOrder = WXTransferMoneyOrderService.self().getByTradeNo(order.getTradeNo());
			            if(wxTransferMoneyOrder != null) {
			                request.setAttribute("transferMoneyOrder", wxTransferMoneyOrder);
			            }
		        	}
		        }
	    	}
	        return "/team/user/transfer_money_order/handle.html";
	    }
	    
	    @Route(value = { "/team/user/transfer_money_order/reject.html" })
	    public String reject(HttpServletRequest request) {
	        return "/team/user/transfer_money_order/reject.html";
	    }

	    /**
	     * 驳回
	     * @param request
	     * @return
	     */
	    @Route(value = { "/team/user/transfer_money_order/reject.do" })
	    public AjaxResult doReject(HttpServletRequest request, HttpSession session) {
	        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"处理失败，请稍后再试");
	        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
	    	if(loginUser == null) {
	            result.setCode(DtoConstants.LOGIN_OVERDUE, "登录过期，请重新登录");
	            return result;
	        }
	        String tradeNo = WebUtils.getString(request,"tradeNo");
	        String operateNote = WebUtils.getString(request,"operateNote");
	        if(StringTools.isNotBlank(tradeNo) && StringTools.isNotBlank(operateNote)) {
	        	UserTransferMoneyOrder order = UserTransferMoneyOrderService.self().getByTradeNo(tradeNo);
			    if(order != null) {
		        	PayAccountGroup accountGroup = PayAccountGroupService.self().getById(order.getAccountGroupId());
		        	if(accountGroup != null && accountGroup.getUserId() != null 
		        			&& accountGroup.getUserId().equals(loginUser.getId())) {
			            OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE,WebConstants.PROGRAM_TYPE_NAME);
			            operateInfo.setOperator( EOperatorType.Agent.index(),loginUser.getFullName());
			            operateInfo.setOperateNote(operateNote);
			            try {
			                if (UserTransferMoneyOrderService.self().reject(tradeNo,operateInfo)) {
			                    result.setCode(DtoConstants.SUCCESS, null);
			                }
			            } catch (LogicException e) {
			                result.setMsg(e.getMessage());
			            }
		        	}
			    }
	        }
	        return result;
	    }
	    
	    @Route(value = { "/team/user/transfer_money_order/success.do" })
	    public AjaxResult doSuccess(HttpServletRequest request, HttpSession session) {
	        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"处理失败，请稍后再试");
	        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
	    	if(loginUser == null) {
	            result.setCode(DtoConstants.LOGIN_OVERDUE, "登录过期，请重新登录");
	            return result;
	        }
	        String tradeNo = WebUtils.getString(request,"tradeNo");
	        Integer handleType = WebUtils.getInteger(request,"handleType");
	        if(StringTools.isNotBlank(tradeNo) && handleType != null) {
	        	UserTransferMoneyOrder order = UserTransferMoneyOrderService.self().getByTradeNo(tradeNo);
			    if(order != null) {
		        	PayAccountGroup accountGroup = PayAccountGroupService.self().getById(order.getAccountGroupId());
		        	if(accountGroup != null && accountGroup.getUserId() != null 
		        			&& accountGroup.getUserId().equals(loginUser.getId())) {
			            OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE,WebConstants.PROGRAM_TYPE_NAME);
			            operateInfo.setOperator( EOperatorType.Agent.index(),loginUser.getFullName());
			            if(UserTransferMoneyOrderEnum.HandleType.OfflineProcessing.index().equals(handleType)){
			                try {
			                    if (UserTransferMoneyOrderService.self().officeProcessing(tradeNo,operateInfo)) {
			                        result.setCode(DtoConstants.SUCCESS, null);
			                    }
			                } catch (LogicException e) {
			                    result.setMsg(e.getMessage());
			                }
			            }else if(UserTransferMoneyOrderEnum.HandleType.ManualProcessing.index().equals(handleType)){
			                try {
			                    if (UserTransferMoneyOrderService.self().manualProcessing(tradeNo,operateInfo)) {
			                        result.setCode(DtoConstants.SUCCESS, null);
			                    }
			                } catch (LogicException e) {
			                    result.setMsg(e.getMessage());
			                }
			            }else{
			                result.setMsg("未知的处理方式");
			            }
		        	}
			    }
	        }
	        return result;
	    }

	    @Route(value = "/team/user/transfer_money_order/operate/list.data")
	    public ListResult<OrderLogContent.LogItem> operateListData(HttpServletRequest request) {
	        ListResult<OrderLogContent.LogItem> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
	        String tradeNo = WebUtils.getString(request,"tradeNo");
	        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
	        if(loginUser != null) {
		        UserTransferMoneyOrder order = UserTransferMoneyOrderService.self().getByTradeNo(tradeNo);
			    if(order != null) {
			    	PayAccountGroup accountGroup = PayAccountGroupService.self().getById(order.getAccountGroupId());
		        	if(accountGroup != null && accountGroup.getUserId() != null 
		        			&& accountGroup.getUserId().equals(loginUser.getId())) {
				        UserTransferMoneyOrderLog orderLog = UserTransferMoneyOrderLogService.self().getByTradeNo(tradeNo);
				        if(orderLog != null && StringTools.isNotBlank(orderLog.getContent())){
				            OrderLogContent orderLogContent = JsonTools.fromJson(orderLog.getContent(),OrderLogContent.class);
				            if(orderLogContent != null && orderLogContent.getItems() != null && orderLogContent.getItems().size() > 0){
				                result.setCode(DtoConstants.SUCCESS,null);
				                result.getBody().setData(orderLogContent.getItems());
				            }
				        }
		        	}
			    }
	        }
	        return result;
	    }
}
